<script setup lang="ts">
import { DateRange } from '$/client'
import moment from 'moment'
import { DatePicker } from 'vexip-ui'
import { computed } from 'vue'

const props = defineProps<{
  type: 'year' | 'month' | 'date' | 'datetime'
}>()
const range = defineModel<DateRange>({ required: true })

const time = computed<number | number[]>({
  get() {
    if (props.type === 'datetime') return [range.value.start, range.value.end]
    return range.value.start
  },
  set(v: any) {
    switch (props.type) {
      case 'date': {
        const date = moment(v)
        range.value = DateRange.inst({ start: date.startOf('day').valueOf(), end: date.endOf('day').valueOf() })
        break
      }
      case 'month': {
        const date = moment(v)
        range.value = DateRange.inst({ start: date.startOf('month').valueOf(), end: date.endOf('month').valueOf() })
        break
      }
      case 'year': {
        const date = moment(v)
        range.value = DateRange.inst({ start: date.startOf('year').valueOf(), end: date.endOf('year').valueOf() })
        break
      }
      case 'datetime':
        range.value = DateRange.inst({ start: v[0], end: v[1] })
        break
    }
  }
})
</script>

<template>
  <DatePicker v-if="type === 'date'" type="date" v-model:value="time" />
  <DatePicker v-else-if="type === 'month'" type="month" v-model:value="time" />
  <DatePicker v-else-if="type === 'year'" type="year" v-model:value="time" />
  <DatePicker v-else-if="type === 'datetime'" type="datetime" v-model:value="time" range />
</template>
